//
//  JSONSearchDAO.m
//  oos4ios
//
//  Created by Pablo Gonzalez on 7/13/11.
//  Copyright 2011 11870.com. All rights reserved.
//

#import "JSONSearchDAO.h"
#import "../../../Atom/Queries/OosQuery.h"

@implementation JSONSearchDAO

@synthesize appToken;

- (void)dealloc
{
    [appToken release];
    [mData release];
    [callback release];
    [ticket release];
    [super dealloc];
}

- (OosQuery *) query
{
    //self.options.queryOptions.alt = @"json";
    OosQuery *query = [super query];
    query.appToken = self.appToken;
    return query;
}

- (OosDaoTicket *) read:(id <IOosDaoReadCallback>)daoCallback
{
    [ticket release];
	ticket = [[OosDaoTicket ticket] retain];
    [callback release];
    callback = [daoCallback retain];
    NSURL *url = [self.query feedURL];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection;
    connection = [[NSURLConnection alloc] initWithRequest: request 
                                                 delegate: self
                                         startImmediately: YES];
    [connection release];
	return ticket;
}

#pragma mark - URLConnecionDelegate

- (void)connection: (NSURLConnection *)connection 
didReceiveResponse: (NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    NSInteger statusCode = [httpResponse statusCode];
    NSLog(@"statusCode = %d", statusCode);
    if (statusCode < 200 || statusCode > 300) {
        NSString *errorMessage =  @"Vaya, ha pasado algo que no esperabamos ";
        if (statusCode > 500) {
            errorMessage =  @"Hay un problema con el servidor";
        } else if (statusCode > 400 || statusCode < 402) {
            errorMessage =  @"El email y/o la contraseña no son correctos";
        }
        
        NSDictionary *props = [NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey];
        
        NSError *error = [NSError errorWithDomain:@"11870.com" 
                                             code:statusCode 
                                         userInfo:props];
        [callback resultedInError:error withTicket:ticket];
//        [self finishTheJob:error];
        
//        [mDelegate performSelector:mSelector withObject:error];
    }
}

- (void)connection:(NSURLConnection *)connection 
    didReceiveData:(NSData *)data
{
    
    if (data && [data isKindOfClass:[NSData class]]) {
        if (!mData) {
            mData = [[NSMutableData dataWithData: data] retain];
        } else {
            [mData appendData:data];
        }
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    id result = nil;
    if (mData) {
        NSString *dataString = [[NSString alloc] initWithData:mData 
                                                     encoding:NSUTF8StringEncoding];
        if (dataString) {
            
        }
    }
    [callback readResult:result withTicket:ticket];
}


@end
